package io.gitee.chearnee.fw.web.page;

import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.Getter;
import lombok.Setter;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

/**
 * @Author: ning
 * @Date: 2021/2/25 15:19
 * @Description:
 */
@Getter
@Setter
public class ResultPage<T> extends QueryPage {

    /**
     * 总页数
     */
    private Long totalPage;
    /**
     * 总条数
     */
    private Long total;
    /**
     * 分页数据
     */
    private List<T> records = new ArrayList<>();

    /**
     * 将PageHelper分页后的list转为分页信息
     */
    public static <T> ResultPage<T> restPage(List<T> list) {
        ResultPage<T> result = new ResultPage<T>();
//        PageInfo<T> pageInfo = new PageInfo<T>(list);
//        result.setTotalPage(pageInfo.getPages());
//        result.setPageNum(pageInfo.getPageNum());
//        result.setPageSize(pageInfo.getPageSize());
//        result.setTotal(pageInfo.getTotal());
//        result.setList(pageInfo.getList());
        return result;
    }

    /**
     * 将SpringData分页后的list转为分页信息
     */
    public static <T> ResultPage<T> restPage(IPage<T> pageInfo) {
        ResultPage<T> result = new ResultPage<>();
        result.setTotalPage(pageInfo.getPages());
        result.setCurrent(pageInfo.getCurrent());
        result.setPageSize(pageInfo.getSize());
        result.setTotal(pageInfo.getTotal());
        result.setRecords(pageInfo.getRecords());
        return result;
    }

    public static <S, R> ResultPage<R> covertPage(ResultPage<S> pageInfo, Function<S, R> consumer) {
        ResultPage<R> resultPage = new ResultPage<>();
        resultPage.setTotalPage(pageInfo.getTotalPage());
        resultPage.setTotal(pageInfo.getTotal());
        resultPage.setCurrent(pageInfo.getCurrent());
        resultPage.setPageSize(pageInfo.getPageSize());
        pageInfo.getRecords().forEach(s -> {
            R t = consumer.apply(s);
            resultPage.getRecords().add(t);
        });
        return resultPage;
    }

    public static <T, S> ResultPage<T> restPage(IPage<S> pageInfo, Function<S, T> consumer) {
        ResultPage<T> result = new ResultPage<>();
        result.setTotalPage(pageInfo.getPages());
        result.setCurrent(pageInfo.getCurrent());
        result.setPageSize(pageInfo.getSize());
        result.setTotal(pageInfo.getTotal());
        pageInfo.getRecords().forEach(s -> {
            T t = consumer.apply(s);
            result.getRecords().add(t);
        });
        return result;
    }
}
